var addLineID = "addQuestionDetail"; //增加行按扭ID
var tableID = "tableQuestionDetail"; //表格ID
var operator = "add";                //记录执行的操作
$(function() {

	initTable2();

	// 绑定问题类型
	bindDict("questionType", "question_item", "");
	
	// 点击新增
	$('#' + addLineID).click(function() {
		var tableData = $('#' + tableID).bootstrapTable('getData');
		var num = 0;
		if(tableData.length > 0){
			num = tableData[tableData.length-1]['QUESTIONORDER'];
		}
		$('#title2').html("新增问题");
		$("#modalMenu2").modal('show');
		$('#num').html(tableData.length + 1);
		$('#questionOrder').val(parseInt(num) + 1);
	});

	$('#save2').click(function() {
		var questionData = {};
		questionData.QUESTIONORDER = $("#questionOrder").val();
		questionData.QUESTION = $("#question").val();
		questionData.QUESTIONTYPE = $("#questionType").val();
		questionData.QUESTIONITEM = $("#questionItem").val();
		if (!check('attach')){
			return true;
		}
		if('add' == operator){
			$('#' + tableID).bootstrapTable('append', questionData);
		} else {
			$('#' + tableID).bootstrapTable('updateRow', {
				index: parseInt($("#num").html()) - 1,
                row: questionData
            });
		}
		$("#modalMenu2").modal('hide');
		
	});
	
	$('#qst').change(function(){
		if('' != $('#qen').val()){
			if(Date.parse($('#qst').val()) > Date.parse($('#qen').val())){
				$('#qen').val('');
			}
		}
		$('#qen').attr('min', $('#qst').val());
	});
	
	//清空表单数据事件
	$("#modalMenu2").on("hidden.bs.modal", function() {
		clearForm();
	});

});

function initTable2() {
	$('#' + tableID).bootstrapTable({
		pagination : false, //分页
		dataType : "json",
		striped : true, //是否显示行间隔色
		formatNoMatches: function(){
			return '单击右上角"新增问题"按钮添加问卷问题';
	    },
		data: [],
		columns : [ {
			field : 'number',
			title : '序号',
			align : 'center',
			width : '80px',
			formatter : function(value, row, index) {
				return index + 1;
			}
		}, {
			field : 'QUESTIONID',
			visible : false
		}, {
			field : 'QUESTIONORDER',
			visible : false
		}, {
			field : 'QUESTION',
			width : '300px',
			title : '问题'
		}, {
			field : 'QUESTIONTYPE',
			width : '100px',
			title : '问题类型',
			formatter : function(value, row, index) {
				if (value == "01") {
					return "单选";
				}
				if (value == "02") {
					return "多选";
				}
			}
		}, {
			field : 'QUESTIONITEM',
			title : '问题选项'
		}, {
			field : 'operate',
			title : '操作',
			align : 'center',
			width : '200px',
			events : operateEvents,
			formatter : operateFormatter
		} ]
	});
}

function operateFormatter(value, row, index) {
	return [
			'<button type="button" class="Edit2 btn btn-warning  btn-sm" style="margin-right:10px;"><span class="glyphicon glyphicon-edit"></span>编辑</button>',
			'<button type="button" class="Delete2 btn btn-danger  btn-sm" style="margin-right:10px;"><span class="glyphicon glyphicon-minus"></span>删除</button>' 
		   ].join('');
}

window.operateEvents = {
	'click .Edit2' : function(e, value, row, index) {
		operator = 'update';
		var questionTypeValue = parseInt(row.QUESTIONTYPE) < 10 ? "0" + parseInt(row.QUESTIONTYPE) : row.QUESTIONTYPE + "";
		$('#title2').html("修改问题");
		$("#modalMenu2").modal('show');
		$("#question").val(row.QUESTION);
		$("#num").html(row.QUESTIONORDER);
		$("#questionType [value=" + questionTypeValue + "]").prop("selected", true);
		$("#questionItem").tagsinput('add', row.QUESTIONITEM);
	},
	'click .Delete2' : function(e, value, row, index) {
		
		window.wxc.xcConfirm('是否<strong>删除</strong>序号[' + (index+1) + ']的数据?', window.wxc.xcConfirm.typeEnum.confirm,{
			onOk:function(v){
				 $('#' + tableID).bootstrapTable('remove', {
		             field: 'QUESTIONORDER',
		             values: [row.QUESTIONORDER]
		         });
			}
		});
	}
};

//保存数据事件
function save(){
	var questionData = {};
	questionData.QUESTIONNAIRETITLE = $("#questionnaireTitle").val();
	questionData.QUESTIONNAIREDISC = $("#disc").val();
	questionData.EFFECTIVESTARTDATE = $("#qst").val();
	questionData.EFFECTIVEENDDATE = $("#qen").val();
	questionData.STATUS = $("input[name='STATUS']:checked").val();
	if (!check('main')){
		return true;
	}
	// 问题数组
	var questionDetailDatas = $('#tableQuestionDetail').bootstrapTable('getData');
	if(questionDetailDatas.length == 0){
		window.wxc.xcConfirm('请添加问卷问题', window.wxc.xcConfirm.typeEnum.error);
		return;
	}
	$.each(questionDetailDatas, function(index, obj){
		obj.QUESTIONORDER = index + 1;
	});
	questionData.questions = questionDetailDatas;
	$.ajax({
		method : 'post',
		url : basePath() + 'question/insert.do',
		data : JSON.stringify(questionData),
		dataType : "json",
		contentType : "application/json",
		success : function(data) {
			if (data.result == 1) {
				parent.closeModal('modalMenu');		//刷新数据
			}
		}
	});

}

function check(filedContent) {
	var result = true;
	var mustStr = "";
	if('main' == filedContent) {
		mustStr = "QUESTIONNAIRETITLE,QUESTIONNAIREDISC,EFFECTIVESTARTDATE,EFFECTIVEENDDATE";
	} else {
		mustStr = "QUESTION,QUESTIONTYPE,QUESTIONITEM";
	}
	var strMsg = "";
	var mustStrs = mustStr.split(',');
	for (var i = 0; mustStr != '' && i < mustStrs.length; i++) {
		var obj = $('[name="' + mustStrs[i] + '"]');
		var obj1 = obj.attr("placeholder");
		if (obj.val() == "") {
			strMsg += obj1.substring(0, 3)
					+ "<span style='color:red;'><strong>"
					+ obj1.substring(3, obj1.lengh) + "</strong></span>！<br />";
			result = false;
		}
	}
	if (strMsg != "") {
		window.wxc.xcConfirm(strMsg, window.wxc.xcConfirm.typeEnum.error);
	}
	return result;
}

function clearForm(){
	$("#questionType option:first").prop("selected", true);
	$("#questionId").val("");
	$('#questionOrder').val("");
	$("#question").val("");
	$("#num").html("");
	var items = $('#questionItem').val();
	if (items.indexOf(",") == -1) {
		$("#questionItem").tagsinput('remove', items);
	} else {
		var a = [];
		a = items.split(",");
		for (var i = 0; i < a.length; i++) {
			var item = a[i];
			$("#questionItem").tagsinput('remove', item);
		}
	}
}